package com.gene.tlonpo.service.remote.common.handler;

import com.alibaba.fastjson.JSON;
import com.gene.tlonpo.guard.GuardDistributedInfo;
import com.gene.tlonpo.guard.tool.GuardAggregationTool;
import com.gene.tlonpo.manager.type.GuardManageType;
import com.gene.tlonpo.service.remote.cache.TlonpoChannelCache;
import com.gene.tlonpo.service.remote.common.model.DataDto;
import com.gene.tlonpo.service.remote.common.model.DataRespDto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @author geneX
 * 客户端handler
 */
@Slf4j
public class TlonpoNettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("[tlonpo client]:tlonpo client -> server build connection success，server:{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        //断开连接的时候清除本地的channel缓存
        log.warn("[tlonpo client]:server connection disconnected,server address:{}", ctx.channel().remoteAddress());
        InetSocketAddress serverAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        TlonpoChannelCache.remove(serverAddress.getHostName(), serverAddress.getPort());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //客户端对结果进行异步打印，请求放不进行结果同步获取
        //如果返回为成功，则将对应guard的分布式数据删除
        //后续版本client端进行同步获取结果，则无需这样处理了
        if (msg instanceof DataRespDto) {
            DataRespDto dataRespDto = (DataRespDto) msg;
            if (dataRespDto.hasSuccess() && dataRespDto.getBackData() != null) {
                GuardAggregationTool.removeGuard(new GuardDistributedInfo(dataRespDto.getBackData()), GuardManageType.DISTRIBUTED);
            }
        }

        log.info("[tlonpo client]:tlonpo server response data,msg:{}", JSON.toJSONString(msg));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.warn("[tlonpo client]:tlonpo client exception,server address:{}", ctx.channel().remoteAddress(), cause);
    }
}
